<!-- subpkg_consult/room/index.vue -->
<script lang="ts" setup>
  import { imageUploadApi, orderDetailApi } from '@/pages/api/consult'
  import useUserStore from '@/pages/store/user'
  import { onLoad } from '@dcloudio/uni-app'
  import { io, type Socket } from 'socket.io-client'
  import roomStatus from './components/room-status.vue'
  import type { OrderDetail } from '@/types/consult'
  import { nextTick, ref } from 'vue'
  import type { Datum, MsgData, MsgItem } from '@/types/room'
  import patientInfo from './components/patient-info.vue'
  import notifyInfo from './components/notify-info.vue'
  import messageInfo from './components/message-info.vue'
  import prescriptionInfo from './components/prescription-info.vue'
  import rateInfo from './components/rate-info.vue'

  // import COS from 'cos-js-sdk-v5'
  // // console.log(COS.version);  sdk 版本需要不低于 1.8.3
  // const cos = new COS({
  //   SecretId: '1333990806', // sts服务下发的临时 secretId
  //   SecretKey: 'AKID1DyjRSdo8V30MveZTOD0gVMDuiYmvxzB', // sts服务下发的临时 secretKey
  // })

  const store = useUserStore()
  let socket: Socket
  const textMessage = ref('')
  const onInputConfirm = () => {
    socket.emit('sendChatMsg', {
      from: store.userId,
      to: orderInfo.value.docInfo.id,
      msgType: 1,
      msg: {
        content: textMessage.value,
      },
    })
    textMessage.value = ''
  }

  const props = defineProps<{
    orderId: string
    payResult: string
  }>()

  //历史消息列表
  const messageList = ref<MsgItem[]>([])

  onLoad(() => {
    //处理支付失败
    if (props.payResult === 'false') {
      uni.switchTab({
        url: '/pages/my/index',
      })
    }
    // 建立连接
    socket = io('https://consult-api.itheima.net', {
      auth: { token: 'Bearer ' + store.token },
      query: { orderId: props.orderId },
      transports: ['websocket', 'polling'],
      timeout: 5000,
    })

    // 监听订单状态改变
    socket.on('statusChange', () => {
      // console.log('订单状态改变')
      getUserInfo()
    })

    //历史消息列表
    socket.on('chatMsgList', (res: MsgData) => {
      // console.log('历史消息列表', res)
      // messageList.value = res.data[0].items
      // console.log('messageList  ----->  ', messageList.value)
      if (res.code !== 10000) return
      res.data?.forEach((items: Datum) => {
        messageList.value.push(
          {
            msgType: 31,
            msg: { content: items.createTime },
            id: items.createTime,
          },
          ...items.items!
        )
      })
      // 滚动到底部
      nextTick(() => {
        sp.value = 'item' + (messageList.value.length - 1)
      })
    })

    socket.on('receiveChatMsg', (message: MsgItem) => {
      socket.emit('updateMsgStatus', message.id)
      // 追加消息
      messageList.value.push(message)

      // 滚动到底部
      nextTick(() => {
        sp.value = 'item' + (messageList.value.length - 1)
      })
    })
  })

  onLoad(() => {
    getUserInfo()
  })

  //定义变量 - 保存订单信息
  const orderInfo = ref({} as OrderDetail)
  const getUserInfo = async () => {
    const res = await orderDetailApi(props.orderId)
    console.log('res  ----->  ', res)
    //保存订单信息
    orderInfo.value = res
  }

  const onSendImage = async () => {
    if (orderInfo.value.status !== 3) {
      return uni.showToast({
        title: '医生不在线',
      })
    }

    const res = await uni.chooseImage({ count: 1 })

    const data = await imageUploadApi(res.tempFilePaths[0])

    socket.emit('sendChatMsg', {
      from: store.userId,
      to: orderInfo.value.docInfo.id,
      msgType: 4,
      msg: {
        picture: {
          id: data.id,
          url: data.url,
        },
      },
    })
  }

  const sp = ref('')

  // 发送视频
  // const onSendImage = async () => {
  //   if (orderInfo.value.status !== 3) {
  //     return uni.showToast({
  //       title: '医生不在线',
  //     })
  //   }

  //   const res = await uni.chooseVideo()
  //   console.log('res  ----->  ', res.tempFile)

  //   cos.uploadFile(
  //     {
  //       Bucket: 'myt-1333990806' /* 填写自己的 bucket，必须字段 */,
  //       Region: 'ap-guangzhou' /* 存储桶所在地域，必须字段 */,
  //       Key: 'xxx.mp4' /* 存储在桶里的对象键（例如:1.jpg，a/b/test.txt，图片.jpg）支持中文，必须字段 */,
  //       Body: res.tempFile, // 上传文件对象
  //       onProgress: function (progressData) {
  //         console.log(JSON.stringify(progressData))
  //       },
  //     },
  //     function (err, data) {
  //       if (err) {
  //         console.log('上传失败', err)
  //       } else {
  //         console.log('上传成功', 'https://' + data.Location)

  //         socket.emit('sendChatMsg', {
  //           // 发送人的id
  //           from: store.userId,
  //           // 医生的id
  //           to: orderInfo.value.docInfo.id,
  //           // 图片消息类型
  //           msgType: 4,
  //           msg: {
  //             picture: {
  //               id: 'xxx',
  //               url: 'https://' + data.Location,
  //             },
  //           },
  //         })
  //       }
  //     }
  //   )
  // }
</script>

<template>
  <view class="room-page">
    <!-- 问诊订单状态 -->
    <room-status :countdown="orderInfo.countdown" :status="orderInfo.status" />
    <scroll-view
      :scroll-into-view="sp"
      refresher-enabled
      refresher-background="#f2f2f2"
      scroll-y
      style="flex: 1; overflow: hidden"
    >
      <view class="message-container">
        <!-- 此处将来填充更多代码... -->
        <view v-for="(item, index) in messageList" :key="item.id" :id="'item' + index">
          <!-- 患者信息 21 -->
          <patient-info v-if="item.msgType === 21" :info="item.msg?.consultRecord" />
          <!-- 系统消息 -->
          <notify-info v-if="item.msgType! >=31" :type="item.msgType!">{{
            item.msg?.content
          }}</notify-info>
          <!-- 接受消息 -->
          <message-info
            :info="item"
            :type="item.msgType"
            v-if="item.msgType === 1 || item.msgType === 4"
          />
          <!-- 处方消息 -->
          <prescription-info v-if="item.msgType === 22" :info="item.msg!" />
          <!-- 医生提示 -->
          <rateInfo
            :order-id="orderId"
            :doc-id="orderInfo.docInfo?.id"
            v-if="item.msgType === 23 || item.msgType === 24"
            :type="item.msgType"
            :info="item.msg!"
          />
        </view>
      </view>
    </scroll-view>

    <!-- 发送消息 -->
    <view class="message-bar">
      <template v-if="true">
        <uni-easyinput
          v-model="textMessage"
          :disabled="orderInfo.status !== 3"
          @confirm="onInputConfirm"
          :clearable="false"
          :input-border="false"
          placeholder-style="font-size: 32rpx; color: #c3c3c5;"
          placeholder="问医生"
        />
        <view class="image-button">
          <uni-icons size="40" color="#979797" type="image" @click="onSendImage"></uni-icons>
        </view>
      </template>
      <button v-else class="uni-button">咨询其它医生</button>
    </view>
  </view>
</template>

<style lang="scss">
  @import './room.scss';
</style>
